package com.hwtx.form.persistence;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hwtx.form.domain.repo.ApiRepo;
import com.hwtx.form.persistence.entity.ApiDef;
import com.hwtx.form.persistence.entity.ApiDefField;
import com.hwtx.form.persistence.mapper.ApiFieldMapper;
import com.hwtx.form.persistence.mapper.ApiMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class ApiRepoImpl extends ServiceImpl<ApiMapper, ApiDef> implements ApiRepo {

    @Resource
    private ApiFieldMapper apiFieldMapper;

    @Override
    public ApiDefField getApiDefField(ApiDefFieldQuery apiDefFieldQuery) {
        return apiFieldMapper.selectOne(getCondition(apiDefFieldQuery));
    }

    @Override
    public List<ApiDefField> getApiDefFields(ApiDefFieldQuery apiDefFieldQuery) {
        LambdaQueryWrapper<ApiDefField> queryWrapper = getCondition(apiDefFieldQuery);
        queryWrapper.orderByAsc(ApiDefField::getNum);
        return apiFieldMapper.selectList(queryWrapper);
    }

    @Override
    public void saveDetails(ApiDefField apiDefField) {
        apiFieldMapper.insert(apiDefField);
    }

    @Override
    public ApiDef getApiDef(String code) {
        return baseMapper.selectOne(new LambdaQueryWrapper<ApiDef>().eq(ApiDef::getCode, code));
    }

    @Override
    public boolean updateById(ApiDefField apiDefField) {
        return apiFieldMapper.updateById(apiDefField) > 0;
    }

    @Override
    public void removeApiFields(ApiDefFieldQuery apiDefFieldQuery) {
        apiFieldMapper.delete(getCondition(apiDefFieldQuery));
    }

    private LambdaQueryWrapper<ApiDefField> getCondition(ApiDefFieldQuery apiDefFieldQuery) {
        LambdaQueryWrapper<ApiDefField> queryWrapper = new LambdaQueryWrapper<>();
        if (apiDefFieldQuery.getModelDetailId() != null) {
            queryWrapper.eq(ApiDefField::getModelDetailId, apiDefFieldQuery.getModelDetailId());
        }
        if (apiDefFieldQuery.getApiCode() != null) {
            queryWrapper.eq(ApiDefField::getApiCode, apiDefFieldQuery.getApiCode());
        }
        if (apiDefFieldQuery.getId() != null) {
            queryWrapper.eq(ApiDefField::getId, apiDefFieldQuery.getId());
        }
        return queryWrapper;
    }
}
